<template>
  <div class="app-container">
    <div class="head-container">
      <!--搜索框-->
      <el-form inline :model="searchForm">
         <el-form-item>
            <el-input
                  v-model="searchForm.name"
                  placeholder="名称"
                  clearable>
            </el-input>
         </el-form-item>
         <el-form-item>
            <el-button @click="getRoleList()">搜索</el-button>
            <el-button type="primary" @click="dialogFormVisible = true" v-permission="['sys:role:save']">新增</el-button>
            <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;">
              <template #reference>
                <el-button type="danger" :disabled="multipleSelection.length === 0" v-permission="['sys:role:delete']">批量删除</el-button>  
              </template>
            </el-popconfirm>
         </el-form-item>
      </el-form>
    </div>
    <el-table 
      ref="table"  
      :data="data" 
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      row-key="id"
      stripe
      default-expand-all
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="code" label="唯一编码" />
      <el-table-column prop="remark" label="描述" />
      <el-table-column prop="statu" label="状态" >
        <template #default="scope">
          <el-tag v-if="scope.row.statu === 0" size="small" type="danger">禁用</el-tag>
          <el-tag v-else-if="scope.row.statu === 1" size="small" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="操作">
        <template #default="scope">
          <el-button size="small" @click="permHandle(scope.row.id)" v-permission="['sys:role:perm']">分配权限</el-button>
          <el-button size="small" type="primary" @click="editHandle(scope.row.id)" v-permission="['sys:menu:update']">编辑</el-button>
          <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)">
            <template #reference>
              <el-button 
                type="danger"
                icon="el-icon-delete"
                size="small"
                v-permission="['sys:menu:delete']"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.current"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.size"
      layout="total, prev, pager, next, sizes"
      :total="total">
    </el-pagination>
    <!--编辑对话框-->
    <el-dialog title="角色信息" v-model="dialogFormVisible" width="600px">
      <el-form :model="editForm" :rules="editFormRules" ref="ruleFormRef">
        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code" label-width="100px">
          <el-input v-model="editForm.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="statu" label-width="100px">
            <el-radio-group v-model="editForm.statu">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
          <el-button type="primary" @click="submitEditForm(ruleFormRef)">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!--权限分配-->
    <el-dialog title="分配权限" v-model="permDialogFormVisible" width="600px">
      <el-form :model="permForm" ref="permFormRef">
        <el-tree
          :data="permTreeData"
          show-checkbox
          ref="permTree"
          :check-strictly=checkStrictly
          node-key="id"
          default-expand-all=true
          :props="defaultProps">
        </el-tree>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="resetForm(permFormRef)">取 消</el-button>
        <el-button type="primary" @click="submitPermForm(permFormRef)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { rolelist, add, edit, info, del, perm } from "@/api/system/role"
import { menulist } from "@/api/system/menu"
import { ElMessage, ElTable, FormInstance, ElTree } from 'element-plus'



const permTreeData = ref([])
const searchForm = reactive({
  name: '',
  current: 1,
  size: 10
})
const current = ref()
const total = ref()
const data = ref([])
// 获取权限列表
const getRoleList = () => {
  rolelist(searchForm).then(res => {
    data.value = res.data.records
    searchForm.current = res.data.current
    searchForm.size = res.data.size
    total.value = res.data.total
  })
  menulist().then(res => {
    permTreeData.value = res.data
    console.log('permTreeData', permTreeData.value)
  })
}
const handleSizeChange = (val: any) => {
  searchForm.size = val
  getRoleList()
}
const handleCurrentChange = (val: any) => {
  searchForm.current = val
  getRoleList()
}


const permFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const editForm = ref({} as RoleDto)
const editFormRules = reactive({
    name: [
      {required: true, message: '请输入名称', trigger: 'blur'}
    ],
    code: [
      {required: true, message: '请输入唯一编码', trigger: 'blur'}
    ],
    statu: [
      {required: true, message: '请选择状态', trigger: 'blur'}
    ]
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
  permDialogFormVisible.value = false
}
const submitEditForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        editForm.value.id ? await edit(editForm.value) : add(editForm.value)
        ElMessage.success(`${editForm.value.id? '编辑': '添加'}成功 `)
        resetForm(formEl)
        getRoleList()
        dialogFormVisible.value = false
      } finally {
        dialogFormVisible.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const editHandle = (id: string) => {
  info(id).then(res => {
    editForm.value = res.data
    dialogFormVisible.value = true
  })
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<RoleDto[]>([])
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
  console.log(val)
} 
const delHandle = async(id: string) => {
  const ids = []
  id ? ids.push(id) : multipleSelection.value.forEach(item => {
    ids.push(item.id)
  });
  try {
    await del(ids)
    getRoleList()
    ElMessage.success('删除成功')
  } catch (error) {
    console.log(error)
  }
}

const permTree = ref<InstanceType<typeof ElTree>>()
const checkStrictly = ref(true)
const treeCheckedKeys = ref([])
const defaultProps = {
  children: 'children',
  label: function(data: any, node: any) {
    return data.name
  },
}
const permForm = ref({} as RoleDto)
const permDialogFormVisible = ref(false)
const permHandle = (id: string) => {
  permDialogFormVisible.value = true
  info(id).then(res => {
    permTree.value!.setCheckedKeys(res.data.menuIds)
    permForm.value = res.data
    console.log("this.treeCheckedKeys")
    console.log(permForm.value.id)
  })
}
const ruleFormRef = ref<FormInstance>()
const submitPermForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  let menuIds = []
  console.log('permForm', permForm.value.id)
  menuIds = permTree.value!.getCheckedKeys()
  
  perm(permForm.value.id, menuIds).then(res => {
    ElMessage.success('操作成功')
    getRoleList()
    permDialogFormVisible.value = false
  })
}

onMounted(() => {
  getRoleList()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>